"use strict";

var config = require('./config');
var fs = require("fs");
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
var routes = require("./app/router");
var path = require('path');var compression = require('compression');


app.use(cookieParser());

app.set("config", config);

// view engine setup
app.set('views', path.join(__dirname, "views"));
app.set('view engine', 'ejs');

app.disable("x-powered-by");
app.use(express.static(path.join(__dirname, 'public')));


//设置ajax响应头
app.use(function(req, res, next) {

    var headers = req.headers;
    var userAgent = headers["user-agent"];
    if (headers["x-requested-with"] === "XMLHttpRequest" || headers['content-type'] === 'application/json') {
        var reg = /MSIE (8|9)\.0/;
        var header = {
            "Content-Type": "application/json;charset=utf-8"
        };
        if (reg.test(userAgent)) {
            header = {
                "Content-Type": "text/plain;charset=utf-8"
            };
            res.set(header);
        } else {
            res.set(header);
        }

    } else{
        header = {
            "Content-Type": "text/html;charset=utf-8"
        };
        res.set(header);
    }

    next();

});


var bodyParser = require('body-parser');
app.use(bodyParser.json()); //body-parser 解析json格式数据
app.use(bodyParser.urlencoded({
    extended: true
}));
app.set('port', config.port);

var dbmanager = require('./app/evn/dbmanager');
dbmanager.init(config);
app.use(routes);

app.use(function(err, req, res, next) {
    console.log('err --- ' + err);
    if (err) {
        res.send(err).end();
    } else {
        res.send({
            success:false
        }).end();
    }

});

// 捕捉404错误并且重定向到index.html界面
app.use(function(req, res, next) {
    console.log('[TRACE] Server 404 request:' + req.originalUrl);
    res.status(200).sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(config.port, function() {
    var nowDate = new Date();
    console.log(nowDate.toLocaleDateString() + ' ' +
        nowDate.toLocaleTimeString());
    console.log('express started on port :' + app.get('port'));
});
